package com.hzhr.iot.collect.protocol.checker;

import com.hzhr.iot.collect.constant.entity.MessagefieldEntity;
import com.hzhr.iot.collect.constant.entity.MessagetmpEntity;
import com.hzhr.iot.collect.constant.entity.constant.MessagefieldEntityConstant;
import com.hzhr.iot.collect.constant.entity.constant.MessagetmpEntityConstant;
import com.hzhr.iot.collect.util.StrUtil;
import org.springframework.stereotype.Component;

@Component
public class Checker1 implements Checker {

    @Override
    public boolean check(String message, int protocolId) {
        MessagetmpEntity messagetmpEntity = MessagetmpEntityConstant.getMessagetmpEntityByProtocolId(protocolId);

        //crc校验
        if (messagetmpEntity.getCrcfieldId() != null) {
            //获取crc
            Integer crcFieldId = messagetmpEntity.getCrcfieldId();
            MessagefieldEntity crcFieldEntity = MessagefieldEntityConstant.MAP.get(crcFieldId);
            Integer fieldStartIndex = (crcFieldEntity.getStartindex() * 2 + message.length()) % message.length();
            Integer fieldSize = crcFieldEntity.getSize() * 2;
            String crc = StrUtil.substringBySize(message, fieldStartIndex, fieldSize);
            crc = StrUtil.reverseUpperAndLowerByte(crc);//高低位取反
            //获取crc目标字节
            Integer crcTargetByteStartIndex = 0;//crc目标字节起始位置
            Integer crcTargetByteEndIndex = message.length() - 6;//crc目标字节结束位置
            String crcTargetByte = StrUtil.substring(message, crcTargetByteStartIndex, crcTargetByteEndIndex);

            if (!crc.equals(StrUtil.getCrc16(StrUtil.hexStr2byte(crcTargetByte)).toUpperCase())) {
                return false;
            }
        }

        return true;
    }
}
